package cn.pconline.autoclub.web.admin;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.dyna.AbstractDyna;

@Controller
@RequestMapping("/admin/dyna")
public class AdminDynaController {
    @Autowired
    private DynaService dynaService;
    @Autowired
    private ClubService clubService;
    
    @RequestMapping(value = "/list.do")
    public String list(HttpServletRequest request, HttpServletResponse response) {
        Date from = WebUtils.parseDate(request, "from");
        Date to = WebUtils.parseDate(request, "to");
         //TODO 模糊查询优化可以考虑用快搜平台
        Calendar fromCal = Calendar.getInstance();
        if(from != null) {
            fromCal.setTime(from);
        } else {
            //fromCal.add(Calendar.DAY_OF_MONTH, fromCal.get(Calendar.DAY_OF_MONTH)-1);
        }
        fromCal = org.apache.commons.lang.time.DateUtils.truncate(fromCal, Calendar.DAY_OF_MONTH);
        
        Calendar toCal = Calendar.getInstance();
        if(to != null) {
            toCal.setTime(to);
        }
        toCal = org.apache.commons.lang.time.DateUtils.truncate(toCal, Calendar.DAY_OF_MONTH);
        
        int fromYear = fromCal.get(Calendar.YEAR);
        int toYear = toCal.get(Calendar.YEAR);
        if(toYear != fromYear) {//不同一年，会跨表，不支持
            //return null;
            fromCal = toCal;
        }
        
        String keyword = WebUtils.param(request, "keyword", null);
        
        AbstractDyna.DynaOrder[] orgerItem = AbstractDyna.DynaOrder.listOrderItem();
        request.setAttribute("orderItem", orgerItem);
        int oidx = WebUtils.paramInt(request, "order", -1);
        AbstractDyna.DynaOrder order =  AbstractDyna.DynaOrder.getOrderItem(oidx);
        
        int pageNo = WebUtils.paramInt(request, "pageNum", 1);
        int pageSize = 20;
        Pager<DynaInfo> pager = dynaService.searchDyna(fromCal.getTime(), toCal.getTime(), keyword, order, pageNo, pageSize, 2);

        request.setAttribute("from", DateUtils.format(fromCal.getTime()));
        request.setAttribute("to", DateUtils.format(toCal.getTime()));
        
        if(pager != null) {
            List<DynaInfo> dynas = pager.getResultList();
            Long[] dynaIds = new Long[dynas.size()];
            int idx = 0;
            for(DynaInfo dyna : dynas) {
                dynaIds[idx++] = dyna.getDynaInfoId();
            }
            request.setAttribute("termPraise", dynaService.getDynaPraise(fromCal.getTime(), toCal.getTime(), dynaIds));
            request.setAttribute("pager", pager);
            /*request.setAttribute("total", pager.getTotal());
            request.setAttribute("pageNo", pager.getPageNo());
            request.setAttribute("list", pager.getResultList());*/
        }
        
        return "admin/dyna/list";
    }
    
    @RequestMapping(value = "/batchExport.do", produces = {"application/octet-stream"})
    public void listBatchExport(HttpServletRequest request, HttpServletResponse response) {
        Date from = WebUtils.parseDate(request, "from");
        Date to = WebUtils.parseDate(request, "to");
        
        //判断所选时间选不能超过一个约月
	    long day = (from.getTime() - to.getTime()) / (24 * 60 * 60 * 1000);  
	    int dayCount = Math.abs(new Long(day).intValue())+1;
	    if(dayCount >31){
	    	from = to;
	    }
        Calendar fromCal = Calendar.getInstance();
        if(from != null) {
            fromCal.setTime(from);
        } else {
            //fromCal.add(Calendar.DAY_OF_MONTH, fromCal.get(Calendar.DAY_OF_MONTH)-1);
        }
        fromCal = org.apache.commons.lang.time.DateUtils.truncate(fromCal, Calendar.DAY_OF_MONTH);
        
        Calendar toCal = Calendar.getInstance();
        if(to != null) {
            toCal.setTime(to);
        }
        toCal = org.apache.commons.lang.time.DateUtils.truncate(toCal, Calendar.DAY_OF_MONTH);
        
        int fromYear = fromCal.get(Calendar.YEAR);
        int toYear = toCal.get(Calendar.YEAR);
        if(toYear != fromYear) {//不同一年，会跨表，不支持
            //return null;
            fromCal = toCal;
        }

        String keyword = WebUtils.param(request, "keyword", null);
        
        int oidx = WebUtils.paramInt(request, "order", -1);
        AbstractDyna.DynaOrder order =  AbstractDyna.DynaOrder.getOrderItem(oidx);
        
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = 2000;
        Pager<DynaInfo> pager = dynaService.searchDyna(fromCal.getTime(), toCal.getTime(), keyword, order, pageNo, pageSize, 2);

        if(pager != null) {
            String[] cellString = new String[]{"ID", "车友会", "内容", "发表人", "发表时间", "回复时间", "回复数", "点赞(时段)", "点赞(总数)", "更新时间"};
            HSSFWorkbook work = new HSSFWorkbook();
            HSSFSheet sheet = work.createSheet("动态列表("+DateUtils.format(fromCal.getTime())+"~"+DateUtils.format(toCal.getTime())+")");
            HSSFRow row = sheet.createRow(0);
            for (int i = 0; i < cellString.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(cellString[i]);
            }
            /**
             * 根据分页数据生成excel文件
             */
            while(pageNo <= pager.getPageCount()) {
                // 数据一页一页加载
                if (pageNo > 1) {
                    pager = dynaService.searchDyna(fromCal.getTime(), toCal.getTime(), keyword, order, pageNo, pageSize, 2);
                }
                for (int i = 0; i < pager.getResultList().size(); i++) {
                    DynaInfo dyna = pager.getResultList().get(i);
                    HSSFRow rowData = sheet.createRow(((pageNo - 1) * pageSize) + i + 1);
                    rowData.createCell(0).setCellValue(dyna.getDynaInfoId());
                    Club club = clubService.getClub(dyna.getClubId());
                    String clubUrl = "";
                    if(club != null) {
                        clubUrl = club.getClubUrl();
                    }
                    rowData.createCell(1).setCellValue(dyna.getClubId()+"("+clubUrl+")");
                    rowData.createCell(2).setCellValue(dyna.getContent());
                    rowData.createCell(3).setCellValue(dyna.getCreateName()+"("+dyna.getCreateBy()+")");
                    rowData.createCell(4).setCellValue(DateUtils.formatDetail(dyna.getCreateDate()));
                    rowData.createCell(5).setCellValue(DateUtils.formatDetail(dyna.getLastPostAt()));
                    rowData.createCell(6).setCellValue(dyna.getPostCount());
                    Map<Long, Integer> praise = dynaService.getDynaPraise(fromCal.getTime(), toCal.getTime(), dyna.getDynaInfoId());
                    //TODO 查点赞数可以按页批量查，导出excel可以参考cn.pconline.officialclub.web.OActivityController的导出方法
                    int termPraise = 0;
                    if(praise != null && praise.get(dyna.getDynaInfoId()) != null) {
                        termPraise = praise.get(dyna.getDynaInfoId());
                    }
                    rowData.createCell(7).setCellValue(termPraise);
                    rowData.createCell(8).setCellValue(dyna.getPraiseCount());
                    rowData.createCell(9).setCellValue(DateUtils.formatDetail(dyna.getUpdateAt()));
                }
                pageNo++;
            }
            try {
                //设置返回数据类型
                response.setContentType("application/vnd.ms-excel;charset=GBK");
                //设置返回的文件名
                response.setHeader("Content-Disposition",
                        "attachment;Filename=dataExport.xls");
                OutputStream out = response.getOutputStream();
                work.write(out);
                out.flush();
                out.close();
            } catch (IOException ex) {
                //log.error("listBatchExport fail!", ex);
            }
        }
    }

}
